package cn.com.bsoft.cloud.service.serviceImpl;

import cn.com.bsoft.cloud.dao.cloud.CloudCompanyDao;
import cn.com.bsoft.cloud.entity.cloud.*;
import cn.com.bsoft.cloud.entity.company.CompanyMess;
import cn.com.bsoft.cloud.entity.company.PTCompanyMess;
import cn.com.bsoft.cloud.entity.param.DeliveryParam;
import cn.com.bsoft.cloud.entity.param.DrugListParam;
import cn.com.bsoft.cloud.service.CloudCompanyService;
import cn.com.bsoft.cloud.utils.ResultCode;
import cn.com.bsoft.immunity.kotlin.JsonExtKt;
import cn.com.bsoft.immunity.utils.HttpUtilsKt;
import kotlin.jvm.internal.Reflection;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional(value="txManagerCloud")
public class CloudCompanyServiceImpl implements CloudCompanyService{

    public static Logger logger = LogManager.getLogger(CloudCompanyServiceImpl.class);

    @Autowired
    private CloudCompanyDao cloudCompanyDao;

//    String url = "http://10.96.36.228/pay/person/sendMsg";
//    String url = "http://172.16.5.35/pay/person/sendMsg";
    String url = "http://172.16.5.35/test/person/sendMsg";

    @Override
    public List<PrescriptionMess> queryDrugList(DrugListParam param) {

        //查询此医院在某段时期内的所有处方list
        List<String> hospitalCodes = param.getHospitalCodes();
        String hosStr = StringUtils.join(hospitalCodes.toArray(), ",");
        //查处方分中心，患者信息,做一对多的映射，查询处方单对应的详情
        List<PrescriptionMess> list=cloudCompanyDao.queryDrugList(param.getStartDate(),param.getEndDate(),hosStr);

        for (PrescriptionMess mess:list) {
            List<PrescriptionDetail> cfmess = mess.getCfmess();
            if(cfmess!=null&&cfmess.size()>0){
                mess.setDetailCount(cfmess.size());
                BigDecimal totalMoney = new BigDecimal("0");
                for (PrescriptionDetail detail:cfmess) {
                    totalMoney=totalMoney.add(detail.getFinancialTransaction());
                }
                mess.setTotalMoney(totalMoney);
            }
        }
        return list;
        /*//查询符合条件的处方id集合
        List<String> prescriptionList=cloudCompanyDao.queryprescriptionList(param.getStartDate(),param.getEndDate(),hosStr);
        //拿出处方id拼接成字符串，去查询处方详细信息list
        String prescriptionStr = StringUtils.join(hospitalCodes.toArray(), ",");
        //查询处方详情list
        List<PrescriptionDetail> detailList=cloudCompanyDao.queryDetailList(prescriptionStr);*/

    }


    @Override
    public Map<String, Object> updateDeliveryStatu(DeliveryParam param) {
        //将处方id以逗号隔开形式封装
        String sqlstr="";
        String[] codeArray = param.getPrescriptionCode().split(",");
        for(int i=0;i<codeArray.length;i++){
            if(i==0){
                sqlstr+="'"+codeArray[i]+"'";
            }else{
                sqlstr+=",'"+codeArray[i]+"'";
            }
        }
        param.setPrescriptionCodeStr(sqlstr);
        HashMap<String, Object> regMsg = new HashMap<String, Object>();
        //查询对应数据是否存在处方
        String[] appointIds=cloudCompanyDao.findMessByParam(param);
        if(appointIds==null||appointIds.length==0){
            regMsg.put("code", ResultCode.ERROR);
            regMsg.put("msg", "不存在对应的处方");
            return regMsg;
        }
        //更改配送状态
        Boolean bool=cloudCompanyDao.updateDeliveryStatu(param);
        if(bool){
            if(param.getStatus().equals("2")){//到达站点，发送通知给app通知患者付费
                //查询拼接短信的相关信息
                SendMess mess=cloudCompanyDao.findMessByCode(codeArray[0]);
                PushMess pushMess = new PushMess();
                pushMess.setSuite("jieyi.mh");
                pushMess.setTitle("温馨提醒");
                pushMess.setContentType("plain/text");
                pushMess.setAction("cloudRemind");//需和app商量
                        try {
                            List<String> listtel = new ArrayList<String>();
                            listtel.add(param.getCardNo());
                            pushMess.setCardNo(listtel);
                            pushMess.setBody(mess.getPatientName()+",您在"+mess.getHospitalName()+"捷医云诊室就诊后需配送的药品，已到达"+mess.getPsdmc()+",请及时携带您的就诊卡(卡号:"+mess.getCardNum()+"),前往"+mess.getAddress()+"取药");
                            pushMess.setExtra(param.getCardNo());
                            URL u1 = new URL(url);
                            HttpUtilsKt.postJson(u1, pushMess, JsonExtKt.getListJavaType(Reflection.createKotlinClass(AppMessageRsp.class)));
                        } catch (Exception e) {
                            String msg="云诊室药品到达通知付费：";
                            logger.error( msg+ e.getMessage(), e);
                            cloudCompanyDao.saveErrorMess(msg,e.getMessage());
                        }
                    }
            regMsg.put("code", ResultCode.SUCCESS);
            regMsg.put("msg", "更改成功");
        }else{
            regMsg.put("code", ResultCode.ERROR);
            regMsg.put("msg", "更改失败");
        }
        return regMsg;
    }


    @Override
    public List<Site> querySitesByCode(String hoscode) {
        List<Site> list=cloudCompanyDao.querySitesByCode(hoscode);
        return list;
    }

    @Override
    public List<CompanyMess> queryCompanyMess(String companyCode) {
        return cloudCompanyDao.queryCompanyMess(companyCode);
    }


    @Override
    public Boolean updateCompanyMess(String companyCode,String companyName,String secret, String publickey) {
        return cloudCompanyDao.uopdateCompanyMess(companyCode,companyName,secret,publickey);
    }

    @Override
    public Boolean addCompanyMess(String companyCode, String companyName, String secret, String publickey) {
        return cloudCompanyDao.addCompanyMess(companyCode,companyName,secret,publickey);
    }

    @Override
    public String findCompanyNameByCode(String companyCode) {
        return cloudCompanyDao.findCompanyNameByCode(companyCode);
    }

    @Override
    public String findCompanyPubkey() {
        return cloudCompanyDao.findCompanyPubkey();
    }


    /**
     * 获取医药公司公钥
     * @param companyCode
     * @return
     */
    @Override
    public String getPublicKey(String companyCode) {
        return cloudCompanyDao.getPublicKey(companyCode);
    }

    /**
     * 获取平台私钥
     * @return
     */
    @Override
    public String getPrivateKey() {
        return cloudCompanyDao.getPrivateKey();
    }

    /**
     * 获取医药公司secret
     * @param companyCode
     * @return
     */
    @Override
    public String getSecret(String companyCode) {
        return cloudCompanyDao.getSecret(companyCode);
    }

    @Override
    public PTCompanyMess getCompanyMess(String companyCode){
        return cloudCompanyDao.getCompanyMess(companyCode);
    }

    /**
     * 查询分站点信息
     * @return
     */
    @Override
    public List<Site> queryAllSiteMess() {
        return cloudCompanyDao.queryAllSiteMess();
    }

    @Override
    public void updateAddressByCode(String siteCode,String siteName, String address) {
        cloudCompanyDao.updateAddressByCode(siteCode,siteName,address);
    }

    @Override
    public List<Site> queryHosList() {
        return cloudCompanyDao.queryHosList();
    }

    @Override
    public List<Site> querySiteByCode(String hosCode) {
        return cloudCompanyDao.querySiteByCode(hosCode);
    }

    @Override
    public void addSiteMess(String hosCode, String hosName, String siteCode, String siteName, String address) {
        cloudCompanyDao.addSiteMess(hosCode,hosName,siteCode,siteName,address);
    }

    @Override
    public String findSiteBySitecode(String siteCode) {
        return cloudCompanyDao.findSiteBySitecode(siteCode);
    }


    @Override
    public void delSiteMessByCode(String siteCode) {
        cloudCompanyDao.delSiteMessByCode(siteCode);
    }

}
